<template>
  <div class="comment-sys-page">
    <el-card>
      <table-bar :show-top="true" :show-bottom="false" @search="search" @reset="clear">
        <template #top>
          <el-form :inline="true" :model="formInline" class="form-search">
            <el-form-item label="举报人昵称">
              <el-input
                  v-model="formInline.reporterName"
                  maxlength="50"
                  placeholder="请输入举报人昵称"
                  clearable
              />
            </el-form-item>
            <el-form-item label="被举报人昵称">
              <el-input
                  v-model="formInline.reportedName"
                  maxlength="30"
                  placeholder="请输入被举报人昵称"
                  clearable
              />
            </el-form-item>
          </el-form>
        </template>
      </table-bar>

      <art-table
          :data="tableData"
          :loading="tableLoading"
          :border="true"
          :total="total"
          :current-page="formInline.page"
          :page-size="formInline.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :show-header-background="true"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="reporterName" label="举报人昵称" min-width="150" />
        <el-table-column prop="reportedName" label="被举报人昵称" min-width="150" />
        <el-table-column prop="reportReason" label="举报原因" min-width="120" align="center" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <button-table type="primary" text="审核" @click="handleAudit(scope.row)" />
          </template>
        </el-table-column>
      </art-table>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
        v-model="dialogVisible.audit"
        title="聊天记录审核"
        width="1200px"
        :close-on-click-modal="false"
        :before-close="handleDialogClose"
        class="audit-dialog"
    >
      <div class="chat-container">
        <!-- 聊天记录区域 -->
        <div class="chat-messages">
          <div class="image-container">
            <!-- 替换为普通图片 + 点击事件 -->
            <img
                v-for="(imgUrl, imgIndex) in images"
                :key="imgIndex"
                :src="imgUrl"
                class="message-image"
                @click="showImageViewer(imgIndex)"
            />
          </div>
        </div>

        <!-- 审核区域 -->
        <div class="audit-section mt-6">
          <el-form :model="auditForm" label-width="100px">
            <el-form-item label="审核结果" required>
              <el-radio-group v-model="auditForm.result" @change="handleResultChange">
                <el-radio label="1">违规</el-radio>
                <el-radio label="2">不违规</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
                label="处理方式"
                required
                v-if="auditForm.result === '1'"
            >
              <el-radio-group v-model="auditForm.handlingMethods">
                <el-radio label="1">禁用用户IM</el-radio>
                <el-radio label="2">禁用单聊</el-radio>
                <el-radio label="3">禁用群聊</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 时长选择 -->
            <el-form-item
                v-if="auditForm.result === '1' && auditForm.handlingMethods!='1'"
                label="禁用单聊时长"
                required
            >
              <el-select v-model="auditForm.disableSingleChatDuration" placeholder="请选择禁用时长">
                <el-option label="1分钟" value="1"></el-option>
                <el-option label="1小时" value="2"></el-option>
                <el-option label="1周" value="3"></el-option>
                <el-option label="1月" value="4"></el-option>
                <el-option label="1年" value="5"></el-option>
                <el-option label="永久" value="6"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="审核备注">
              <el-input
                  v-model="auditForm.remark"
                  type="textarea"
                  rows="3"
                  placeholder="请输入审核备注"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <el-button @click="dialogVisible.audit = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
      </template>
    </el-dialog>
    <!-- 手动添加图片查看器组件 -->
    <el-image-viewer
        v-if="imageViewerVisible"
        :url-list="images"
        :initial-index="imageViewerIndex"
        @close="imageViewerVisible = false"
        class="custom-image-viewer"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { GetAll } from '@/api/IMReportApi'
import {
  IMReportGetAllParam,
  IMReport,
} from '@/api/model/IMReportModel'
import { ApiStatus } from '@/utils/http/status'
import ArtTable from '@/components/Table/ArtTable.vue'
import TableBar from '@/components/Table/TableBar.vue'
import ButtonTable from '@/components/Form/ButtonTable.vue'
import axios from 'axios'

// 表单和表格数据
let formInline = ref<IMReportGetAllParam>({
  page: 1,
  pageSize: 10,
  reporterName: '',
  reportedName: ''
})
let tableLoading = ref(false)
let total = ref(0)
let tableData = ref<IMReport[]>([])
const imageViewerVisible = ref(false)
const imageViewerIndex = ref(0)

// 显示图片查看器
function showImageViewer(index: number) {
  imageViewerIndex.value = index
  imageViewerVisible.value = true
}
// 对话框状态
let dialogVisible = ref({
  view: false,
  audit: false
})

// 审核相关数据
let currentReport = ref<IMReport>({} as IMReport)
let chatMessages = ref<any[]>([])
let loadingChat = ref(true)
let chatError = ref(false)
let auditForm = reactive({
  result: '', // 'violate' 违规, 'noViolate' 不违规
  handlingMethods:'', // 处理方式
  remark: '' ,// 审核备注
  disableSingleChatDuration: ''
})

onMounted(() => {
  getAll(formInline.value)
})

// 获取所有举报列表
async function getAll(params: IMReportGetAllParam) {
  try {
    tableLoading.value = true
    const requestData: any = {
      page: params.page,
      pageSize: params.pageSize,
      reporterNname: params.reporterName,
      reportedNname: params.reportedName
    }

    // 移除值为 undefined 的字段
    Object.keys(requestData).forEach((key) => {
      if (requestData[key] === undefined || requestData[key] === '') {
        delete requestData[key]
      }
    })

    const res = await GetAll(requestData as IMReportGetAllParam)
    if (res.code === ApiStatus.success) {
      tableData.value = res.data?.list || []
      total.value = res.data?.total || 0

    }
  } catch (error) {
    console.error('获取举报列表失败:', error)
    ElMessage.error('获取举报列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 分页大小变化
function handleSizeChange(val: number) {
  formInline.value.pageSize = val
  getAll(formInline.value)
}

// 当前页码变化
function handleCurrentChange(val: number) {
  formInline.value.page = val
  getAll(formInline.value)
}

// 搜索
function search() {
  total.value = 0
  formInline.value.page = 1
  getAll(formInline.value)
}

// 重置
function clear() {
  formInline.value = {
    page: 1,
    pageSize: 10,
    reporterName: '',
    reportedName: ''
  }
  getAll(formInline.value)
}
const images = ref([])
// 处理审核
async function handleAudit(row: IMReport) {
  currentReport.value = row
  // 重置审核表单
  resetAuditForm()
  // 先显示对话框
  dialogVisible.value.audit = true
  // 加载聊天记录
  console.log("row.reportImages"+row.reportImages);
  images.value= parseImages(row.reportImages)
  //打印图片
  console.log(images.value)

}

function parseImages(imageStr: string): string[] {
  if (!imageStr) return []
  return imageStr.split(',').map(url => url.trim()).filter(url => url.length > 0)
}
// 定义默认聊天记录数据
function getDefaultChatMessages() {
  return [
    {
      "From_Account": "user1",
      "To_Account": "user2",
      "MsgSeq": 1456,
      "MsgRandom": 23287,
      "MsgTimeStamp": 1584669601,
      "MsgFlagBits": 0,
      "IsPeerRead": 1,
      "MsgKey": "1456_23287_1584669601",
      "MsgBody": [
        {
          "MsgType": "TIMTextElem",
          "MsgContent": {
            "Text": "msg 13"
          }
        }
      ],
      "CloudCustomData": "your cloud custom data"
    },
    {
      "From_Account": "user2",
      "To_Account": "user1",
      "MsgSeq": 9806,
      "MsgRandom": 14,
      "MsgTimeStamp": 1584669602,
      "MsgFlagBits": 0,
      "IsPeerRead": 1,
      "MsgKey": "9806_14_1584669602",
      "MsgBody": [
        {
          "MsgType": "TIMTextElem",
          "MsgContent": {
            "Text": "msg 14"
          }
        }
      ],
      "CloudCustomData": "your cloud custom data"
    }
  ].sort((a, b) => a.MsgTimeStamp - b.MsgTimeStamp)
}

// 格式化时间戳
function formatTime(timestamp: number) {
  const date = new Date(timestamp * 1000)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 审核结果变更
function handleResultChange(val: string) {
  if (val !== '1') {
    auditForm.handlingMethods =''
  }
}

// 重置审核表单
function resetAuditForm() {
  auditForm.result = ''
  auditForm.handlingMethods =''
  auditForm.remark = ''
}

// 提交审核
async function submitAudit() {
  if (!auditForm.result) {
    return ElMessage.warning('请选择审核结果')
  }

  if (auditForm.result === 'violate' && auditForm.handlingMethods.length === 0) {
    return ElMessage.warning('请选择处理方式')
  }

  try {
    // 这里可以调用实际的审核提交接口
    console.log('提交审核', {
      reportId: currentReport.value.reportId,
      result: auditForm.result,
      handlingMethods: auditForm.handlingMethods,
      remark: auditForm.remark
    })

    // 模拟接口请求
    await new Promise(resolve => setTimeout(resolve, 500))

    ElMessage.success('审核提交成功')
    dialogVisible.value.audit = false
    // 刷新列表
    getAll(formInline.value)
  } catch (error) {
    console.error('提交审核失败:', error)
    ElMessage.error('提交审核失败，请重试')
  }
}

// 关闭对话框时重置
function handleDialogClose() {
  resetAuditForm()
  chatMessages.value = []
  // 确保对话框关闭
  dialogVisible.value.audit = false
}
</script>

<style scoped>
.chat-container {
  max-height: 70vh;
  display: flex;
  flex-direction: column;
}



.message-item {
  display: flex;
  margin-bottom: 15px;
  max-width: 80%;
}

.message-item.sent {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  margin-right: 10px;
}

.message-item.sent .message-avatar {
  margin-right: 0;
  margin-left: 10px;
  background-color: #67c23a;
}

.message-content {
  background-color: #f5f7fa;
  padding: 10px 15px;
  border-radius: 6px;
  position: relative;
}

.message-item.sent .message-content {
  background-color: #e6f7ff;
}

.message-sender {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.message-text {
  margin-bottom: 5px;
  line-height: 1.5;
}

.message-time {
  font-size: 11px;
  color: #999;
  text-align: right;
}

.audit-section {
  padding-top: 10px;
  border-top: 1px solid #e5e7eb;
}

.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  padding: 15px;
  max-height: 500px;  /* 限制容器高度，超出可滚动 */
  overflow-y: auto;
  background-color: #f9f9f9;
  border-radius: 8px;
  justify-content: flex-start;
}

.message-image {
  width: 200px;
  height: 200px;
  object-fit: contain;
  border-radius: 6px;
  cursor: zoom-in;
  background-color: #fff;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.message-image:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
/* 关键：强制图片查看器层级最高 */
:deep(.custom-image-viewer) {
  z-index: 9999 !important;
}

/* 降低对话框层级 */
:deep(.audit-dialog .el-dialog__wrapper) {
  z-index: 1000 !important;
}
/* 优化滚动条 */
.image-container::-webkit-scrollbar {
  width: 8px;
}

.image-container::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 4px;
}

.image-container::-webkit-scrollbar-track {
  background-color: #f0f0f0;
}

/* 1. 降低审核对话框及其遮罩层的层级 */
.audit-dialog  {
  z-index: 1 !important; /* 对话框容器 */
}


</style>
